﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

// Support functions for /SetList/Edit view

// SongListLoaded(): Called by MVC AJAX when our async song list has been loaded or reloaded
function SongListLoaded() {
    // Initialize the page behavior for our set lists
    InitSetLists();
}

// SongDragEnd(): Called by the JQueryUI handler after a song has been dragged
function SongDragEnd(event, ui) {
    // Update our set list totals
    UpdateTotals();
    // Color/uncolor the songs to denote duplicates
    CheckForDuplicates();
}

// SongDragStop() Called by JQueryUI when a song from a set list is done dragging
// Check if they dragged out of our list, if so, delete song
function SetListSongDragStop(event, ui) {

  var offsetXPos = parseInt(ui.offset.left );
  var offsetYPos = parseInt(ui.offset.top);

  // Determine if we dragged out.  Get current setlist positions
  var obj = $("#setlist_wrapper");
  var boxLeftPos = obj.position().left;
  var boxTopPos = obj.position().top;
  //alert("Left/Top: " + obj.position().left + ", " + obj.position().top);
  //alert("Size: " + obj.width() + ", " + obj.height());
  //alert("Drag stopped!\n\nOffset: (" + offsetXPos + ", " + offsetYPos + ")\n");

  if (offsetXPos < boxLeftPos) {
      // We've dragged out.  Delete item.
      ui.item.remove();
      // Update our set list totals
      UpdateTotals();
      // Color/uncolor the songs to denote duplicates
      CheckForDuplicates();
  }

}

// Check for duplicate songs IDs and turns them yellow
function CheckForDuplicates() {
    // Reset coloring of all songs
    $(".songLI").removeClass("yellow");
    $("#setlist_wrapper .songLI").removeClass("checksong");
    $("#songlist_wrapper .songLI").removeClass("checksong");

    // Iterate through our list items, adding the song ID from each one
    var arr = new Array();
    $("#setlist_wrapper .songLI").each(function () {
        arr.push($(this).attr("data-itemid"));
    });

    // Sort our array
    var sorted_arr = arr.sort();
    var results = [];

    // Find duplicates
    for (var i = 0; i < arr.length - 1; i += 1) {
        if (sorted_arr[i + 1] == sorted_arr[i]) {
            results.push(sorted_arr[i]);
        }
    }

    // Turn the duplicates yellow
    $("#setlist_wrapper .songLI").each(function () {
        for (i = 0; i < results.length; i += 1) {
            if ($(this).attr("data-itemid") == results[i]) {
                $(this).addClass("yellow");
            }
        }
    });

    // Turn the songs already in the set list green
    $("#songlist_wrapper .songLI").each(function () {
        for (i = 0; i < arr.length; i += 1) {
            if ($(this).attr("data-itemid") == arr[i]) {
                $(this).addClass("checksong");
                //alert("removing " + arr[i]);
            }
        }
    });


}

// Initializes our set list behavior on our page: dragging, open/close
function InitSetLists() {
    // Init behaviour for our set lists
    $(".connectedSortable").sortable({
        connectWith: ".connectedSortable",
        dropOnEmpty: true,
        opacity: 0.6,
        placeholder: 'placeholder-highlight',
        distance: 10,
        tolerance: 'pointer',
        update: SongDragEnd,
        stop: SetListSongDragStop
        }).disableSelection();

    // Init behaviour for song list
    $(".connectedDragable li").draggable({
        connectToSortable: ".connectedSortable",
        helper: "clone",
        revert: "invalid",
        distance: 10,
        stop: SongDragEnd
    }).disableSelection();

    // Set up our "hide/show" behaviour for each of our sets
    $("h2.trigger").unbind(); // do this in case this function gets called a second time

    $("h2.trigger").toggle(function () {
        $(this).addClass("active");
    }, function () {
        $(this).removeClass("active");
    });
    $("h2.trigger").click(function () {
        $(this).next(".toggle_container").slideToggle("slow,");
    });

}


// Converts given number of seconds into number of minutes
function SecToMin(length_sec) {
    var secs = length_sec % 60;
    var mins = (length_sec - secs) / 60;
    return mins;
}

// UpdateTotals() updates our "Set List Totals" based on the current
// contents of our set list unordered lists
function UpdateTotals() {
    // Iterate each of our lists with class ".setlistUL"
    $("ul.setlistUL").each(function (index, elem) {
        var songlength = 0;
        var songcount = 0;

        // For each of our UL lists, sum each of our LI items's songlength
        $(this).find("li").each(function () {
            songlength += parseInt($(this).attr("data-songlength"));
            songlength += 60; // PAUSE HACK: add 60 seconds per song to account for pauses between songs
            songcount++;
        });

        // Place into the "Set Length" div we've created.  Div's naming is same as
        // our current item plus "total"
        var newdivname = "#" + $(this).attr("id") + "total";
        $(newdivname).html(SecToMin(songlength) + " minutes (" + songcount + " songs)");
        // alert(index + ": songlength = " + songlength + ", divname = " + newdivname);
    });

}

// Adds new set to our DOM and makes it draggable
function AddSet() {
    // Search to find our new set number
    var latestsetlist = $("ul.setlistUL").last().attr("id");
    var newsetlist_id = parseInt(latestsetlist.substring(3)) + 1;

    // Create new HTML for list and append to end of our SetListWrapper div
    var newHTML = "<h2 class='trigger'><a href='#'>Set " + newsetlist_id + "</a></h2>" +
                "<div class='toggle_container'><div><ul id='set" + newsetlist_id + "' class='draglist connectedSortable setlistUL'>" +
                "</ul><div id='set" + newsetlist_id + "total' class='settotal'>Length: 0 minutes</div></div></div>";
    $('#setlist_wrapper').append(newHTML);

    // Reinitialize Dragging
    InitSetLists();
};

// Sorting functions for song list. Uses jQuery 'tinysort' plugin.
function SortSongListNameASC() {
    $("#dl_songlist>li").tsort({ order: "asc" });
}
function SortSongListNameDSC() {
    $("#dl_songlist>li").tsort({ order: "desc" });
}
function SortSongListSoloistASC() {
    $("#dl_songlist>li").tsort(".node_singer", { order: "asc" });
}
function SortSongListSoloistDSC() {
    $("#dl_songlist>li").tsort(".node_singer", { order: "desc" });
}

// Saves Set List
// Pulls all the requisite DOM data from our page here, makes a JSON object, and sends it
// via AJAX to our server.
function SaveSetList() {
    var songlist_arr = [];
    // Iterate each of our set lists (they have class ".setlistUL")
    $("ul.setlistUL").each(function (index, elem) {

        songlist_arr[index] = []; // init array

        // Iterate each "LI" which is a song or a note
        $(this).find("li").each(function () {

            // Get itemid
            var songid = $(this).attr("data-itemid");

            // If it's a Note, get the note text, put into our array
            if (songid == "Note") {
                var notetext = $(this).find(".node_note").text();
                songlist_arr[index].push(notetext);
            }
            else {
                // if it's a song, put the songID in our array
                songlist_arr[index].push(songid);
            }
        });
    });

    // Get values from our page
    var setlistid = $("#SetListID").val();
    var setlistname = $('#spansetname').text();
    var setlistdate = $('#spansetdate').text();
    var setlisttime = $('#spansettime').text();

    // Create our object.  This object must match the object defined in SetListController.cs
    var data = {
        Name: setlistname,
        Date: setlistdate,
        Time: setlisttime,
        SetListID: setlistid,
        SetArray: songlist_arr
    };

    $.ajax({
        type: "POST",
        url: "/SetList/SaveSetList",
        data: $.toJSON(data),
        dataType: 'json', // This is our return datatype
        contentType: "application/json; charset=utf-8", // send datatype
        success: function (data) {
            // success.  Redirect to index of setlists.
            window.location = "/SetList";
        },
        error: function (data) {
            // get the result and display error to user
            var message = "ERROR: " + data.Message;
            alert(message);
        }
    });
}

